#include "task.h"
#include <stdexcept>

Task::Task(int id, const std::string& description, Priority priority, const std::string& dueDate)
    : _id(id), _description(description), _priority(priority) {
    if (!isValidDate(dueDate)) {
        throw std::invalid_argument("无效的日期格式，请使用YYYY-MM-DD格式");
    }
    this->_dueDate = dueDate;
}

int Task::getId() const { return _id; }
std::string Task::getDescription() const { return _description; }
Priority Task::getPriority() const { return _priority; }
std::string Task::getDueDate() const { return _dueDate; }

void Task::setDescription(const std::string& description) 
{
    this->_description = description;
}

void Task::setPriority(Priority priority) 
{
    this->_priority = priority;
}

void Task::setDueDate(const std::string& dueDate) 
{
    if (!isValidDate(dueDate)) {
        throw std::invalid_argument("无效的日期格式，请使用YYYY-MM-DD格式");
    }
    this->_dueDate = dueDate;
}

std::string Task::toString() const 
{
    std::ostringstream oss;
    oss << "ID: " << _id 
        << " | 描述: " << _description 
        << " | 优先级: " << priorityToString(_priority)
        << " | 截止日期: " << _dueDate;
    return oss.str();
}

std::string Task::priorityToString(Priority priority) 
{
    switch (priority) {
        case Priority::LOW: return "低";
        case Priority::MEDIUM: return "中";
        case Priority::HIGH: return "高";
        default: return "未知";
    }
}

Priority Task::stringToPriority(const std::string& priorityStr) 
{
    if (priorityStr == "低" || priorityStr == "low") return Priority::LOW;
    if (priorityStr == "中" || priorityStr == "medium") return Priority::MEDIUM;
    if (priorityStr == "高" || priorityStr == "high") return Priority::HIGH;
    throw std::invalid_argument("无效的优先级值");
}

bool Task::isValidDate(const std::string& date) const 
{
    if (date.length() != 10) return false;
    if (date[4] != '-' || date[7] != '-') return false;
    
    try {
        int year = std::stoi(date.substr(0, 4));
        int month = std::stoi(date.substr(5, 2));
        int day = std::stoi(date.substr(8, 2));
        
        if (year < 1800 || year > 3000) return false;
        if (month < 1 || month > 12) return false;
        if (day < 1 || day > 31) return false;
        
        // 简单的月份天数验证
        if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) {
            return false;
        }
        
        // 二月处理 (不考虑闰年)
        if (month == 2 && day > 28) {
            return false;
        }
        
        return true;
    } catch (...) {
        return false;
    }
}